// 储蓄统计相关功能

// 初始化储蓄统计
function initializeSavingsStatistics() {
    // 获取储蓄数据
    const savingsData = getSavingsData();
    
    // 渲染储蓄趋势图
    renderSavingsTrendChart(savingsData);
    
    // 渲染储蓄目标完成度图
    renderSavingsGoalChart(savingsData);
}

// 获取储蓄数据
function getSavingsData() {
    // 初始化储蓄管理器
    const savingsManager = new window.AppData.SavingsManager();
    const transactionManager = new window.AppData.TransactionManager();
    
    // 获取储蓄目标
    const savingsGoals = savingsManager.getSavingsGoals();
    const savingsProgress = savingsManager.getCurrentSavingsProgress();
    
    // 获取所有交易
    const transactions = transactionManager.getTransactions();
    
    // 获取所有收入交易并按月分组
    const incomeByMonth = groupIncomeByMonth(transactions);
    
    // 计算每月储蓄金额
    const savingsByMonth = {};
    Object.keys(incomeByMonth).forEach(month => {
        let monthlySavings = 0;
        savingsGoals.forEach(goal => {
            const savingRate = goal.savingRate / 100;
            monthlySavings += incomeByMonth[month] * savingRate;
        });
        savingsByMonth[month] = monthlySavings;
    });
    
    return {
        savingsGoals,
        savingsProgress,
        incomeByMonth,
        savingsByMonth
    };
}

// 按月分组收入交易
function groupIncomeByMonth(transactions) {
    const incomeByMonth = {};
    
    // 过滤出收入交易
    const incomeTransactions = transactions.filter(t => t.type === 'income');
    
    // 按月分组
    incomeTransactions.forEach(transaction => {
        const date = new Date(transaction.date);
        const month = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
        
        if (!incomeByMonth[month]) {
            incomeByMonth[month] = 0;
        }
        
        incomeByMonth[month] += transaction.amount;
    });
    
    return incomeByMonth;
}

// 渲染储蓄趋势图
function renderSavingsTrendChart(savingsData) {
    // 获取数据
    const { incomeByMonth, savingsByMonth } = savingsData;
    
    // 准备图表数据
    const months = Object.keys(incomeByMonth).sort();
    const incomeData = months.map(month => incomeByMonth[month]);
    const savingsData = months.map(month => savingsByMonth[month]);
    
    // 计算累计储蓄
    const cumulativeSavings = [];
    let cumulative = 0;
    savingsData.forEach(amount => {
        cumulative += amount;
        cumulativeSavings.push(cumulative);
    });
    
    // 格式化月份标签
    const formattedMonths = months.map(month => {
        const [year, monthNum] = month.split('-');
        return `${year}年${parseInt(monthNum)}月`;
    });
    
    // 初始化图表
    const trendChart = echarts.init(document.getElementById('savingsTrendChart'));
    
    // 配置图表选项
    const option = {
        tooltip: {
            trigger: 'axis',
            formatter: function(params) {
                let result = params[0].name + '<br/>';
                params.forEach(param => {
                    result += param.seriesName + ': ' + '¥' + param.value.toFixed(2) + '<br/>';
                });
                return result;
            }
        },
        legend: {
            data: ['月收入', '月储蓄', '累计储蓄'],
            textStyle: {
                color: 'rgba(255, 255, 255, 0.7)'
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: formattedMonths,
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)'
            }
        },
        yAxis: {
            type: 'value',
            axisLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.3)'
                }
            },
            splitLine: {
                lineStyle: {
                    color: 'rgba(255, 255, 255, 0.1)'
                }
            },
            axisLabel: {
                color: 'rgba(255, 255, 255, 0.7)',
                formatter: function(value) {
                    return '¥' + value.toFixed(0);
                }
            }
        },
        series: [
            {
                name: '月收入',
                type: 'line',
                data: incomeData,
                smooth: true,
                lineStyle: {
                    width: 2,
                    color: 'rgba(38, 222, 129, 0.8)'
                },
                itemStyle: {
                    color: 'rgba(38, 222, 129, 0.8)'
                }
            },
            {
                name: '月储蓄',
                type: 'bar',
                data: savingsData,
                barWidth: '40%',
                itemStyle: {
                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                        { offset: 0, color: 'rgba(46, 134, 222, 0.9)' },
                        { offset: 1, color: 'rgba(46, 134, 222, 0.5)' }
                    ])
                }
            },
            {
                name: '累计储蓄',
                type: 'line',
                data: cumulativeSavings,
                smooth: true,
                symbolSize: 8,
                lineStyle: {
                    width: 3,
                    color: 'rgba(255, 159, 67, 0.8)'
                },
                itemStyle: {
                    color: 'rgba(255, 159, 67, 0.8)'
                }
            }
        ],
        backgroundColor: 'transparent'
    };
    
    // 设置图表选项
    trendChart.setOption(option);
    
    // 响应窗口大小变化
    window.addEventListener('resize', function() {
        trendChart.resize();
    });
}

// 渲染储蓄目标完成度图
function renderSavingsGoalChart(savingsData) {
    // 获取数据
    const { savingsProgress } = savingsData;
    
    // 如果没有储蓄目标，则不渲染图表
    if (savingsProgress.length === 0) {
        document.getElementById('savingsGoalChart').innerHTML = '<div class="empty-state-text">暂无储蓄目标</div>';
        return;
    }
    
    // 准备图表数据
    const goalData = savingsProgress.map(goal => {
        return {
            name: goal.name || '储蓄目标',
            value: goal.percentage,
            target: goal.targetAmount,
            saved: goal.savedAmount,
            remaining: goal.remaining,
            savingRate: goal.savingRate
        };
    });
    
    // 初始化图表
    const goalChart = echarts.init(document.getElementById('savingsGoalChart'));
    
    // 配置图表选项
    const option = {
        tooltip: {
            formatter: function(params) {
                return `
                    <div style="font-weight: bold; margin-bottom: 5px;">${params.name}</div>
                    <div>目标金额: ¥${params.data.target.toFixed(2)}</div>
                    <div>已储蓄: ¥${params.data.saved.toFixed(2)}</div>
                    <div>剩余: ¥${params.data.remaining.toFixed(2)}</div>
                    <div>完成度: ${params.data.value.toFixed(1)}%</div>
                    <div>储蓄率: ${params.data.savingRate}%</div>
                `;
            }
        },
        series: [
            {
                type: 'gauge',
                startAngle: 90,
                endAngle: -270,
                pointer: {
                    show: false
                },
                progress: {
                    show: true,
                    overlap: false,
                    roundCap: true,
                    clip: false,
                    itemStyle: {
                        color: function(params) {
                            // 根据完成度设置不同颜色
                            const percent = params.data.value;
                            if (percent < 30) {
                                return '#FF5E62';
                            } else if (percent < 70) {
                                return '#FFBE26';
                            } else {
                                return '#26DE81';
                            }
                        }
                    }
                },
                axisLine: {
                    lineStyle: {
                        width: 20,
                        color: [[1, 'rgba(255, 255, 255, 0.1)']]
                    }
                },
                splitLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    show: false
                },
                title: {
                    fontSize: 14,
                    color: 'rgba(255, 255, 255, 0.7)',
                    offsetCenter: [0, '-20%']
                },
                detail: {
                    width: 50,
                    height: 14,
                    fontSize: 18,
                    color: '#fff',
                    formatter: '{value}%',
                    offsetCenter: [0, 0]
                },
                data: goalData
            }
        ],
        backgroundColor: 'transparent'
    };
    
    // 设置图表选项
    goalChart.setOption(option);
    
    // 响应窗口大小变化
    window.addEventListener('resize', function() {
        goalChart.resize();
    });
}

// 导出函数
window.SavingsStatistics = {
    initializeSavingsStatistics,
    getSavingsData,
    renderSavingsTrendChart,
    renderSavingsGoalChart
}; 